package com.zby.charity.controller;


import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zby.charity.common.BaseResponse;
import com.zby.charity.common.ErrorCode;
import com.zby.charity.common.ResultUtils;
import com.zby.charity.dao.PostsDao;
import com.zby.charity.entity.CommentsEntity;
import com.zby.charity.entity.PostsEntity;
import com.zby.charity.entity.ProjectEntity;
import com.zby.charity.entity.UserEntity;
import com.zby.charity.entity.vo.CommentsVo;
import com.zby.charity.entity.vo.PostArrayVo;
import com.zby.charity.entity.vo.PostArrayVos;
import com.zby.charity.entity.vo.PostsVo;
import com.zby.charity.exception.BusinessException;
import com.zby.charity.service.CommentsService;
import com.zby.charity.service.PostsService;
import com.zby.charity.service.UserService;
import com.zby.charity.utils.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zby
 * @email 2069189112@qq.com
 * @date 2025-01-13 14:04:17
 */
@RestController
@Slf4j
@RequestMapping("charity/posts")
public class PostsController {
    @Autowired
    private PostsService postsService;
    @Autowired
    private UserService userService;
    @Autowired
    private PostsDao postsDao;
    @Autowired
    private CommentsService commentsService;

    /*  @PostMapping("/add")
      public BaseResponse<Boolean> publishProject(@RequestBody PostArrayVo posts, HttpServletRequest request) {
          if (posts == null)
              throw new BusinessException(ErrorCode.PARAMS_ERROR);
          UserEntity loginUser = userService.getLoginUser(request);
          if (loginUser == null || !loginUser.getId().equals(posts.getAuthorId()))
              throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
          Integer authorId = posts.getAuthorId();
          UserEntity byId = userService.getById(authorId);
          if (byId == null)
              throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
          String content = posts.getContent();
          String title = posts.getTitle();
          if (StringUtils.isAnyBlank(content, title))
              throw new BusinessException(ErrorCode.PARAMS_ERROR);
          String[] background = posts.getBackground();
          PostsEntity postsEntity = new PostsEntity();
          BeanUtils.copyProperties(posts, postsEntity);
          if (background == null) {
              boolean save = postsService.save(postsEntity);
              if (!save)
                  throw new BusinessException(ErrorCode.OPERATION_ERROR);
              return ResultUtils.success(true);
          }
          String join = String.join(",", Arrays.asList(background));
          postsEntity.setBackground(join);
          boolean save = postsService.save(postsEntity);
          if (!save)
              throw new BusinessException(ErrorCode.OPERATION_ERROR);
          return ResultUtils.success(true);
      }*/
    @PostMapping("/add")
    public BaseResponse<Boolean> publishProject(@RequestBody PostArrayVo postArrayVo, HttpServletRequest request) {
        if (postArrayVo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }

        UserEntity loginUser = userService.getLoginUser(request);
        if (loginUser == null || !loginUser.getId().equals(postArrayVo.getAuthorId())) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录或权限不足");
        }

        Optional.ofNullable(postArrayVo.getTitle())
                .orElseThrow(() -> new BusinessException(ErrorCode.PARAMS_ERROR, "标题不能为空"));
        Optional.ofNullable(postArrayVo.getContent())
                .orElseThrow(() -> new BusinessException(ErrorCode.PARAMS_ERROR, "内容不能为空"));

        PostsEntity postsEntity = new PostsEntity();
        BeanUtils.copyProperties(postArrayVo, postsEntity);

        String background = Optional.ofNullable(postArrayVo.getBackground())
                .map(Arrays::asList)
                .map(list -> String.join(",", list))
                .orElse(null);
        postsEntity.setBackground(background);

        boolean save = postsService.save(postsEntity);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "发布帖子失败");
        }

        return ResultUtils.success(true);
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateProject(@RequestBody PostArrayVos postArrayVo, HttpServletRequest request) {
        if (postArrayVo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }

        UserEntity loginUser = userService.getLoginUser(request);
        if (loginUser == null || !loginUser.getId().equals(postArrayVo.getAuthorId())) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录或权限不足");
        }

        Optional.ofNullable(postArrayVo.getTitle())
                .orElseThrow(() -> new BusinessException(ErrorCode.PARAMS_ERROR, "标题不能为空"));
        Optional.ofNullable(postArrayVo.getContent())
                .orElseThrow(() -> new BusinessException(ErrorCode.PARAMS_ERROR, "内容不能为空"));

        PostsEntity postsEntity = new PostsEntity();
        BeanUtils.copyProperties(postArrayVo, postsEntity);

        String background = Optional.ofNullable(postArrayVo.getBackground())
                .map(Arrays::asList)
                .map(list -> String.join(",", list))
                .orElse(null);
        postsEntity.setBackground(background);
        System.out.println(postsEntity);
        boolean update = postsService.updateById(postsEntity);
        if (!update) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更改帖子失败");
        }

        return ResultUtils.success(true);
    }

    @GetMapping("/list")
    public BaseResponse<List<PostsVo>> list() {
       /* List<PostsEntity> list = postsService.list();
        List<PostsVo> PostsVoList= list.stream().map(postsEntity -> {
            Integer authorId = postsEntity.getAuthorId();
            if (authorId == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
            UserEntity byId = userService.getById(authorId);
            String name = byId.getName();
            PostsVo postsVo = new PostsVo();
            BeanUtils.copyProperties(postsEntity, postsVo);
            postsVo.setAuthorName(name);
            return postsVo;
        }).collect(Collectors.toList());

        return ResultUtils.success(PostsVoList);*/
        List<PostsEntity> postsEntities = Optional.ofNullable(postsService.list()).orElse(Collections.emptyList());

        // 提取所有作者ID
        Set<Integer> authorIds = postsEntities.stream()
                .map(PostsEntity::getAuthorId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 批量获取用户信息
        Map<Integer, UserEntity> userMap = userService.getUserMapByIds(new ArrayList<>(authorIds));

        List<PostsVo> postsVoList = postsEntities.stream().map(postsEntity -> {
            PostsVo postsVo = new PostsVo();
            BeanUtils.copyProperties(postsEntity, postsVo);

            Integer authorId = postsEntity.getAuthorId();
            if (authorId != null && userMap.containsKey(authorId)) {
                String authorName = userMap.get(authorId).getName();
                postsVo.setAuthorName(authorName);
            } else {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }

            return postsVo;
        }).collect(Collectors.toList());

        return ResultUtils.success(postsVoList);
    }

    @GetMapping("/listPostById")
    public BaseResponse<List<PostsEntity>> listPostByAuthorId(@RequestParam("authorId") int authorId) {
        if (authorId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserEntity byId = userService.getById(authorId);
        if (byId == null)
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        QueryWrapper<PostsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("author_id", authorId);
        List<PostsEntity> list = postsService.list(queryWrapper);
        return ResultUtils.success(list);
    }

    @GetMapping("/getById")
    public BaseResponse<PostsEntity> getById(@RequestParam("id") int id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取数据并处理边界条件
        try {
            PostsEntity byId = postsService.getById(id);
            if (byId == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
            return ResultUtils.success(byId);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

    }

    @GetMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> deleteById(@RequestParam("id") int id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "Invalid ID");
        }

        try {
            // 删除帖子
            boolean postDeleted = postsService.removeById(id);
            if (!postDeleted) {
                log.error("Failed to delete post with ID: {}", id);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "帖子删除失败");
            }

            // 删除评论
            boolean commentsDeleted = commentsService.remove(new QueryWrapper<CommentsEntity>().eq("pid", id));
            if (!commentsDeleted) {
                log.error("Failed to delete comments for post ID: {}", id);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "评论删除失败");
            }

            return ResultUtils.success(true);
        } catch (BusinessException e) {
            log.error("Business exception occurred while deleting post with ID {}: {}", id, e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("Unexpected error occurred while deleting post with ID {}: {}", id, e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "Unexpected error occurred");
        }
    }
}
